//
//  MyCouponListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/21.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "MyCouponListCell.h"
#import "CommonCouponEventModel.h"

#import "StrictElectionListViewController.h"

#import "ProductDetailViewController.h"

#import "StoreHotelDetailViewController.h"
#import "StoreDetailViewController.h"
#import "ServiceCatSubSegViewController.h"
#import "FreeNewProductViewController.h"
#import "SearchResultSegViewController.h"
#import "SearchResultSegViewController.h"


#import "MyCouponListViewController.h"

@interface MyCouponListViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, strong) NSMutableArray <CommonCouponModel *>*dataArray;



@end

@implementation MyCouponListViewController

- (instancetype)initWith:(NSInteger)index {
    self = [super init];
    if (self) {
        switch (index) {
            case 0:{
                self.type = MyCouponListType_unUsed;
            } break;
            case 1:{
                self.type = MyCouponListType_Used;
            } break;
            case 2:{
                self.type = MyCouponListType_overDue;
            } break;
            default:
                break;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
    [self refreshParam];
    [self request_myCoupon];
}

- (void)refreshParam {
    self.pageNum = 1;
    self.pageSize = 20;
}

- (void)initView {
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.dataArray.count;
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.dataArray[indexPath.row].itemHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MyCouponListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCouponListCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (self.type) {
        case MyCouponListType_unUsed:{
            
            switch (self.dataArray[indexPath.row].scoType) {
                case CouponType_all:{
                    [self.navigationController popViewControllerAnimated:NO];
                    [[TT_TabbarViewController shareTabbar] setCurrentIndex:TT_TabbarIndexType_Home];

                } break;
                case CouponType_industry:{
                    
                    if (self.dataArray[indexPath.row].classId > 0) {
                        
                        if (self.dataArray[indexPath.row].classId == Store_Category_Hotel_int) {

                            SearchResultSegViewController *vc = [[SearchResultSegViewController alloc] init];
                            vc.keyWord = @"酒店";
                            [self.navigationController pushViewController:vc animated:YES];
                            
                        } else {
                            
                            ServiceCatSubSegViewController *vc = [[ServiceCatSubSegViewController alloc] init];
                            vc.scId = self.dataArray[indexPath.row].classId;
                            [self.navigationController pushViewController:vc animated:YES];
                        }

                    } else {
                     
                        [SVProgressHUD showErrorWithStatus:@"未获取到该行业id"];
                        [SVProgressHUD dismissWithDelay:1];
                    }
                    
                } break;
                case CouponType_union:{

                    StrictElectionListViewController *vc = [[StrictElectionListViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                } break;
                case CouponType_storeAll:{

                    //套餐商家   酒店商家
//                    if (self.dataArray[indexPath.row].classId) {
                        [self request_couponTypeWitnIndex:indexPath.row AndType:1];
//                    } else {
//                        [self.navigationController popToRootViewControllerAnimated:NO];
//                        [[TT_TabbarViewController shareTabbar] setCurrentIndex:TT_TabbarIndexType_Category];
//                    }
                    
                } break;
                case CouponType_storeProduct:{
                    
                    [self request_couponTypeWitnIndex:indexPath.row AndType:2];
                    
                } break;
                case CouponType_userNew:{
                    
                    FreeNewProductViewController *vc = [[FreeNewProductViewController alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    
                } break;
                default:{

                } break;
            }
            
        } break;
            
        default:
            break;
    }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"MyCouponListCell" bundle:nil] forCellReuseIdentifier:@"MyCouponListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_myCoupon];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_myCoupon];
        }];
        
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (NSMutableArray<CommonCouponModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (void)request_myCoupon {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:@(self.type) forKey:@"status"];
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];

    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_myCoupon];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在获取优惠券列表"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];

        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                 
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                        }
                        
                        for (int i=0; i < list.count; i++) {
                            NSDictionary *sysCouponListDic = list[i];
                            CommonCouponModel *couponModel = [CommonCouponModel modelWithDictionary:sysCouponListDic];
                            couponModel.itemHeight = (TTScreenWidth - 30)/3.19 + 20;
                            [weakSelf.dataArray addObject:couponModel];
                        }
                        
                        if (weakSelf.dataArray.count == 0) {
                            
                            if (weakSelf.tableview) {
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_NoCoupon btnTitle:@"" didPressButton:^{}];
                            }
                        }
                        
                        [weakSelf.tableview reloadData];
                    }
                    
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (void)request_couponTypeWitnIndex:(NSInteger)index AndType:(NSInteger)type{
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:@(type) forKey:@"type"];

    switch (type) {
        case 1:{//商家
            [dic setValue:self.dataArray[index].sellerId forKey:@"typeId"];
        } break;
        case 2:{//商品
            [dic setValue:self.dataArray[index].scoGoodsId forKey:@"typeId"];
        } break;
        default:
            break;
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_couponType];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在获取跳转数据"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];

        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {

                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                CommonCouponEventModel *model = [CommonCouponEventModel modelWithDictionary:resultDic];
                
                switch (model.type) {
                    case 1:{//特殊
                        
                        switch (type) {
                            case 1:{//商家  酒店
                                
                                StoreHotelDetailViewController *vc = [[StoreHotelDetailViewController alloc] init];
                                vc.storeId = weakSelf.dataArray[index].sellerId;
                                [weakSelf.navigationController pushViewController:vc animated:YES];
                            } break;
                            case 2:{//商品  婚品
                                
                                ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
                                vc.goodsId = weakSelf.dataArray[index].scoGoodsId;
                                [weakSelf.navigationController pushViewController:vc animated:YES];
                            } break;
                            default:
                                break;
                        }
                        
                    } break;
                    case 2:{//非特殊
                        
                        switch (type) {
                            case 1:{//商家  套餐商家

                                StoreDetailViewController *vc = [[StoreDetailViewController alloc] init];
                                vc.storeId = weakSelf.dataArray[index].sellerId;
                                [weakSelf.navigationController pushViewController:vc animated:YES];
                                
                            } break;
                            case 2:{//商品  套餐
                                
                                CommonCouponModel *model = weakSelf.dataArray[index];
                                
                                CommonPackageModel *packageModel = [[CommonPackageModel alloc] init];
                                packageModel.goodsId = model.scoGoodsId;
                                packageModel.goodsVersion = model.goodsVersion;
                                packageModel.classId = [NSString stringWithFormat:@"%ld",model.classId];
                                
                                [[TT_JumpManager sharedManager] jumpWithDetailModel:packageModel completion:^(BOOL success, NSString * _Nonnull message) {}];
                                
                            } break;
                            default:
                                break;
                        }
                        
                    } break;
                    case 3:{//全部分类
                        [self.navigationController popToRootViewControllerAnimated:NO];
                        //[[TT_TabbarViewController shareTabbar] setCurrentIndex:TT_TabbarIndexType_Category];
                    } break;
                    default:
                        break;
                }

            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}
@end
